//
//  DDVideoView.m
//  hellomui
//
//  Created by zhangtao on 15/10/30.
//  Copyright © 2015年 zt.td. All rights reserved.
//

#import "DDVideoView.h"

static void *PlayViewCMTimeValue = &PlayViewCMTimeValue;
static void *AVPlayerDemoPlaybackViewControllerStatusObservationContext = &AVPlayerDemoPlaybackViewControllerStatusObservationContext;
@implementation DDVideoView
/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */


//-(void)dealloc{
//    NSLog(@"调用了调用了调用了。。。。。。");
//    [self.player replaceCurrentItemWithPlayerItem:_playerItem];
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVAudioSessionRouteChangeNotification object:nil];
//    [self removeObserver:self.player.currentItem forKeyPath:@"status"];
//    [[NSNotificationCenter defaultCenter]removeObserver:self];
//    self.playerItem = nil;
//    self.player = nil;
//    
//    //    [self removeNotification];
//}

-(id)initWithFrame:(CGRect)frame{
    
    if (self =[super initWithFrame:frame]) {
        // 初始化代码
        
        
        NSString *urlStr = [NSString stringWithFormat:@"%@", NSUSER_DEF(@"VIDEOURL")];
        
        NSURL *sourceMovieURL = [NSURL URLWithString:urlStr];

        
        AVAsset *movieAsset = [AVURLAsset URLAssetWithURL:sourceMovieURL options:nil];
        self.playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];
        self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
        
     /* ---- avplayerLayer --- **/
        _playerLayer =[AVPlayerLayer playerLayerWithPlayer:self.player];
//        self.frame = CGRectMake(0,self.dificultVC.navigationController.navigationBar.frame.size.height, MAIN_WIDTH, self.dificultVC.view.frame.size.height -CGRectGetHeight(self.infoView.frame)-10)];
        _playerLayer.videoGravity=AVLayerVideoGravityResizeAspectFill;//视频填充模式
        _playerLayer.frame = CGRectMake(0, 0, MAIN_WIDTH, self.frame.size.height-40);
//        _playerLayer.frame = self.layer.bounds;

        [self.layer addSublayer:_playerLayer];
        [self.player play];
        
        //////
         _playView = [[UIView alloc]initWithFrame:CGRectMake(0, self.frame.size.height-40, self.frame.size.width, 40)];
        _playView.backgroundColor = [UIColor whiteColor];

        _previousBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.frame.size.width/4-20, 10, 20, 20)];
        [_previousBtn setBackgroundImage:[UIImage imageNamed:@"front"] forState:UIControlStateNormal];
        [_previousBtn addTarget:self action:@selector(previous) forControlEvents:UIControlEventTouchUpInside];
        _nextBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.frame.size.width*3/4-5,10,20 ,20)];
        [_nextBtn setBackgroundImage:[UIImage imageNamed:@"next"] forState:UIControlStateNormal];
        [_nextBtn addTarget:self action:@selector(next) forControlEvents:UIControlEventTouchUpInside];
        
        _playOrPauseBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.frame.size.width/2-17, 4, 32, 32)];

        [_playOrPauseBtn setImage:[UIImage imageNamed:@"start_2.png"] forState:UIControlStateNormal];
        [_playOrPauseBtn addTarget:self action:@selector(playOrPause) forControlEvents:UIControlEventTouchUpInside];
        
         [self addSubview:_playView];
        [_playView addSubview:_previousBtn];
        [_playView addSubview:_nextBtn];
        [_playView addSubview:_playOrPauseBtn];
        
       
        
        /*********/
        
        _bigBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, MAIN_WIDTH, self.frame.size.height - 140)];
        [_bigBtn addTarget:self action:@selector(bigButton) forControlEvents:UIControlEventTouchUpInside];
        
        [self addSubview:_bigBtn];
        
        /*********/
        self.lowView = [[UIView alloc]initWithFrame:CGRectMake(0,self.frame.size.height-80, MAIN_WIDTH,40)];
        self.lowView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.5];
       
        self.sBtn = [[UIButton alloc]initWithFrame:CGRectMake(MAIN_WIDTH-40, 8 , 24, 24)];
        [self.sBtn addTarget:self action:@selector(changeScreen) forControlEvents:UIControlEventTouchUpInside];
        [_sBtn setImage:[UIImage imageNamed:@"quanping.png"] forState:UIControlStateNormal];
        
        self.slider = [[UISlider alloc]initWithFrame:CGRectMake(45, 5, 200, 30)];
        self.slider.minimumValue = 0.0;
        self.slider.maximumValue = CMTimeGetSeconds(movieAsset.duration);
        self.slider.value = 0.0;//指定初始值
        [self.slider addTarget:self action:@selector(updateValue:) forControlEvents:UIControlEventTouchUpInside];//设置响应事件
       
        self.slider = [[UISlider alloc]initWithFrame:CGRectMake(10, 10, _lowView.frame.size.width - 50, 20)];
        self.slider.tintColor = [UIColor greenColor];
        self.slider.minimumValue = 0.0;
        self.slider.maximumValue = CMTimeGetSeconds(movieAsset.duration);
        self.slider.value = 0.0;//指定初始值
        [self.slider addTarget:self action:@selector(updateValue:) forControlEvents:UIControlEventTouchUpInside];//设置响应事件
        [self.slider setMaximumTrackImage:[UIImage imageNamed:@"圆角矩形-2"] forState:UIControlStateNormal];
        [self.slider setMinimumTrackImage:[UIImage imageNamed:@"圆角矩形-1-拷贝-2"] forState:UIControlStateNormal];
//        [self.slider setMaximumTrackTintColor:RGB(150, 150, 150, .75)];
      
         [self.slider setThumbImage:[UIImage imageNamed:@"detail_icon_schedule_ball_green.png"] forState:UIControlStateNormal];
        [self.lowView addSubview:_sBtn];
        [self.lowView addSubview:_slider];
        
        [self addSubview:self.lowView];
        
        /*********/
        _centerBtn = [[UIButton alloc]initWithFrame:CGRectMake(_playerLayer.frame.size.width/2-20, _playerLayer.frame.size.height/2-20-30, 40, 40)];
        [_centerBtn addTarget:self action:@selector(playOrPause) forControlEvents:UIControlEventTouchUpInside];
        
        [_centerBtn setImage:[UIImage imageNamed:@"组2"] forState:UIControlStateNormal];

        [self addSubview:_centerBtn];
        
        
        /****** 单击的 Recognizer  ******/
//        UITapGestureRecognizer* singleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTapFrom)];
//        singleRecognizer.numberOfTapsRequired = 1; // 单击
//        [self addGestureRecognizer:singleRecognizer];
        
        [self.playerItem addObserver:self
                          forKeyPath:@"status"
                             options:NSKeyValueObservingOptionNew
                             context:AVPlayerDemoPlaybackViewControllerStatusObservationContext];
        [self initScrubberTimer];
        
    }
    [[self player] pause];
    return self;
    
}




- (double)duration
{  
    AVPlayerItem *playerItem = [[self player] currentItem];
    
    if ([playerItem status] == AVPlayerItemStatusReadyToPlay)
        return CMTimeGetSeconds([[playerItem asset] duration]);
    else
        return 0.f;
}

- (double)currentTime
{
    return CMTimeGetSeconds([[self player] currentTime]);
}

- (void)setCurrentTime:(double)time
{
    [[self player] seekToTime:CMTimeMakeWithSeconds(time, 1)];
}


-(void)dealloc{
    NSLog(@"dealloc");
    [self.player replaceCurrentItemWithPlayerItem:self.playerItem];
}


//
//-(id)initWithCoder:(NSCoder *)aDecoder{
//    NSLog(@"~~~~~~~~~~~~");
//    
//    
//    if ((self = [super initWithCoder:aDecoder])) {
//        
//        AVAudioSession *session = [AVAudioSession sharedInstance];
//        [session setCategory:AVAudioSessionCategoryPlayback error:nil];
//        [session setActive:YES error:nil];
//        
//        [_player setVolume:1];
//        
//        NSLog(@"~!~!~!~!~!~!");
//        
//        
//    }
//    return self;
//}
-(void)over{
    NSLog(@"overover");
    [[self player] pause];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
//    [self.playerItem removeObserver:self forKeyPath:@"status"];
    
    [self.playerItem removeObserver:self forKeyPath:@"status" context:AVPlayerDemoPlaybackViewControllerStatusObservationContext];
}

- (void)playOrPause{
    
    if ([[self player] rate] != 1.f) {
        if ([self currentTime] == [self duration])
            [self setCurrentTime:0.f];
        [[self player] play];
        [_playOrPauseBtn setImage:[UIImage imageNamed:@"stop.png"] forState:UIControlStateNormal];
        [_centerBtn setImage:[UIImage imageNamed:@"组1"] forState:UIControlStateNormal];

       
    } else {
        [[self player] pause];
        [_playOrPauseBtn setImage:[UIImage imageNamed:@"start_2.png"] forState:UIControlStateNormal];
        [_centerBtn setImage:[UIImage imageNamed:@"组2"] forState:UIControlStateNormal];
            }
    
//    CMTime time = [self.player currentTime];
//    NSLog(@"%lld",self.playerItem.duration.value/self.playerItem.duration.timescale);
//    NSLog(@"%lld",time.value/time.timescale);
    
}

#pragma mark - 手势方法
- (void)handleSingleTapFrom{
    
    [UIView animateWithDuration:0.5 animations:^{
        
        if (self.alpha == 0.0) {
            self.alpha = 1.0;
        }else{
            self.alpha = 0.0;
        }
        
    } completion:^(BOOL finish){
        
    }];
}

#pragma mark - slider
- (void)updateValue:(UISlider *)slider{
    
    NSLog(@"ddv!~~~slider");
    
    [self.player seekToTime:CMTimeMakeWithSeconds(slider.value, 1)];
    
    
    if ([[self player] rate] != 1.f) {
        if ([self currentTime] == [self duration])
            [self setCurrentTime:0.f];
        [[self player] play];
    }
    
}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    /* AVPlayerItem "status" property value observer. */
    if (context == AVPlayerDemoPlaybackViewControllerStatusObservationContext)
    {
        
        AVPlayerStatus status = [[change objectForKey:NSKeyValueChangeNewKey] integerValue];
        switch (status)
        {
                /* Indicates that the status of the player is not yet known because
                 it has not tried to load new media resources for playback */
            case AVPlayerStatusUnknown:
            {
                
            }
                break;
                
            case AVPlayerStatusReadyToPlay:
            {
                /* Once the AVPlayerItem becomes ready to play, i.e.
                 [playerItem status] == AVPlayerItemStatusReadyToPlay,
                 its duration can be fetched from the item. */
                
                [self initScrubberTimer];
                
            }
                break;
                
            case AVPlayerStatusFailed:
            {
                
            }
                break;
        }
    }
    
}

#pragma  maik - 监听
-(void)initScrubberTimer
{
    double interval = .1f;
    
    CMTime playerDuration = [self playerItemDuration];
    if (CMTIME_IS_INVALID(playerDuration))
    {
        return;
    }
    double duration = CMTimeGetSeconds(playerDuration);
    if (isfinite(duration))
    {
        CGFloat width = CGRectGetWidth([self.slider bounds]);
        interval = 0.5f * duration / width;
    }
    NSLog(@"interva === %f",interval);
    
    __weak typeof(self) weakSelf = self;
    
    /* Update the scrubber during normal playback. */
    [weakSelf.player addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(interval, NSEC_PER_SEC)
                                                  queue:NULL /* If you pass NULL, the main queue is used. */
                                             usingBlock:^(CMTime time)
     {
         [self syncScrubber];
     }];
    
}


/* Set the scrubber based on the player current time. */
- (void)syncScrubber
{
    CMTime playerDuration = [self playerItemDuration];
    if (CMTIME_IS_INVALID(playerDuration))
    {
        self.slider.minimumValue = 0.0;
        return;
    }
    
    double duration = CMTimeGetSeconds(playerDuration);
    if (isfinite(duration))
    {
        float minValue = [self.slider minimumValue];
        float maxValue = [self.slider maximumValue];
        double time = CMTimeGetSeconds([self.player currentTime]);
        [self.slider setValue:(maxValue - minValue) * time / duration + minValue];
    }
}

- (CMTime)playerItemDuration
{
    AVPlayerItem *playerItem = [self.player currentItem];
//    NSLog(@"%ld",playerItem.status);
    if (playerItem.status == AVPlayerItemStatusReadyToPlay)
    {
        return([playerItem duration]);
    }
    
    return(kCMTimeInvalid);
}
















-(void)layoutSubviews{
    [super layoutSubviews];
    NSLog(@"111");
    UIDeviceOrientation interfaceOrientation=[[UIApplication sharedApplication] statusBarOrientation];
    if (interfaceOrientation == UIDeviceOrientationPortrait || interfaceOrientation == UIDeviceOrientationPortraitUpsideDown) {
//        //翻转为竖屏时
//        
        [self shu];
    }else
        if (interfaceOrientation==UIDeviceOrientationLandscapeLeft || interfaceOrientation == UIDeviceOrientationLandscapeRight) {
        //翻转为横屏时
        [self heng];
        //        [self setHorizontalFrame];
        //        [self.player play];
    }
    
}

-(void)heng{
    self.dificultVC.infoView.hidden = YES;
    self.playView.hidden = YES;
    
    self.frame = CGRectMake(0, 0, MAIN_WIDTH, MAIN_HEIGHT);
    self.lowView.frame = CGRectMake(0,self.frame.size.height-30, MAIN_WIDTH,30);
    _bigBtn.frame = CGRectMake(0, 0, MAIN_WIDTH, self.frame.size.height - 30);
    
    
    self.sBtn.frame = CGRectMake(MAIN_WIDTH-30, 3, 24, 24);
    
    _slider.frame = CGRectMake(20, 12.5, _lowView.frame.size.width - 70, 20);
    
    NSLog(@"heng");
    self.dificultVC.tabBarController.tabBar.hidden = YES;
    self.dificultVC.navigationController.navigationBar.hidden = YES;
    //    self.frame = CGRectMake(0, 0, MAIN_WIDTH, MAIN_HEIGHT);
    _playerLayer.frame = self.frame;
    
    _centerBtn.frame = CGRectMake(_playerLayer.frame.size.width/2-15, _playerLayer.frame.size.height/2-15, 30, 30);
    
}

-(void)shu{
    self.dificultVC.infoView.hidden = NO;
    self.playView.hidden = NO;
    self.dificultVC.navigationController.navigationBar.hidden = NO;

    self.frame = CGRectMake(0, CGRectGetMaxY(self.dificultVC.navigationController.navigationBar.frame), MAIN_WIDTH, MAIN_HEIGHT-self.dificultVC.infoView.frame.origin.y-self.dificultVC.navigationController.navigationBar.frame.size.height-20);
    
    
    
    ///////
    //        self.frame = CGRectMake(0,self.dificultVC.navigationController.navigationBar.frame.size.height, MAIN_WIDTH, self.dificultVC.view.frame.size.height -CGRectGetHeight(self.infoView.frame)-10)];
    _playerLayer.frame = CGRectMake(0, 0, MAIN_WIDTH, self.frame.size.height-40);
    //        _playerLayer.frame = self.layer.bounds;
    
    //////
    _playView.frame = CGRectMake(0, self.frame.size.height-40, self.frame.size.width, 40);
    
    _previousBtn.frame = CGRectMake(self.frame.size.width/4-20, 10, 20, 20);
   
    
    _nextBtn.frame = CGRectMake(self.frame.size.width*3/4-5,10,20 ,20);
  
    
    _playOrPauseBtn.frame =CGRectMake(self.frame.size.width/2-17, 4, 32, 32);
    

    
    
    
    /*********/
    
    _bigBtn.frame = CGRectMake(0, 0, MAIN_WIDTH, self.frame.size.height - 140);
   
    
    /*********/
    self.lowView.frame = CGRectMake(0,self.frame.size.height-80, MAIN_WIDTH,40);
       self.sBtn.frame = CGRectMake(MAIN_WIDTH-40, 8 , 24, 24);
    
    
    self.slider.frame = CGRectMake(45, 5, 200, 30);
       self.slider.frame = CGRectMake(10, 10, _lowView.frame.size.width - 50, 20);
        /*********/
    _centerBtn.frame = CGRectMake(_playerLayer.frame.size.width/2-20, _playerLayer.frame.size.height/2-20-30, 40, 40);
    
    

    
    
    
    
    
    
    
//    self.frame = CGRectMake(0, CGRectGetMaxY(self.dificultVC.navigationController.navigationBar.frame), MAIN_WIDTH,  MAIN_HEIGHT- self.dificultVC.infoView.frame.size.height-CGRectGetMaxY(self.dificultVC.navigationController.navigationBar.frame) -10);
//    //        self.frame = _dificultVC.container.frame;
//    _playView.frame = CGRectMake(0, self.frame.size.height-40, self.frame.size.width, 40);
//    _playerLayer.frame = CGRectMake(0, 0, MAIN_WIDTH, self.frame.size.height-40);
//    
//    NSLog(@"shu");
//    
//    self.lowView.frame = CGRectMake(0,self.frame.size.height-70, MAIN_WIDTH,30);
//    self.lowView.backgroundColor = RGB(36, 36, 36, .7);
//    _bigBtn.frame = CGRectMake(0, 0, MAIN_WIDTH, self.frame.size.height - 40 - _lowView.frame.size.height);
//    _slider.frame = CGRectMake(25, 5, _lowView.frame.size.width - 80, 20);
//    self.sBtn.frame = CGRectMake(MAIN_WIDTH-38, 5, 20, 20);
//    
//    _centerBtn.frame = CGRectMake(_playerLayer.frame.size.width/2-15, _playerLayer.frame.size.height/2-15, 30, 30);
//    
//    self.dificultVC.tabBarController.tabBar.hidden = NO;
//    self.dificultVC.navigationController.navigationBar.hidden = NO;
//    
}


-(void)bigButton{
    _centerBtn.hidden =
    _lowView.hidden = !_lowView.hidden;
    if (_centerBtn.hidden == NO) {
        _countTime = 5;
        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(downTime:) userInfo:nil repeats:YES];
    }
}
-(void)downTime:(NSTimer *)timer{
    _countTime -- ;
    if (_countTime==0) {
        [timer invalidate];
        _centerBtn.hidden = _lowView.hidden = YES;
    }
}


-(void)changeScreen{
    [ToolObjc showMessage:@"旋转手机可自动全屏或半屏"];
    
}

-(void)next{
    [self initPlay:@"next"];
    [[MBProgressController sharedInstance]showWithText:@"正在加载"];

}

-(void)previous{
//    self.player = nil;
//    [self over
//     ];
    [self initPlay:@"prev"];
    [[MBProgressController sharedInstance]showWithText:@"正在加载"];

}



-(void)initPlay:(NSString *)sel{
    
    NSString *path = @"secondClass/getPrevAndNextVideo";
    //
    NSString *userId = [NSString stringWithFormat:@"%@",NSUSER_DEF(@"USERID")];
    NSString *videoId =  [NSString stringWithFormat:@"%@" ,self.dificultVC.idValue];
    NSString *bookId;
    NSString *flag = sel;
    NSDictionary *dicss;
    NSDictionary *dicVal;
    //
    NSLog(@"~~%@~~~%@",self.bookid,self.dificultVC.bookId);
    if (!self.dificultVC.bookId) {
        [ToolObjc showMessage:@"暂无相关信息"];
    }else{
        //
        NSString *bookid = [NSString stringWithFormat:@"%@",self.dificultVC.bookId];
        if (self.bookid) {
            bookid = [NSString stringWithFormat:@"%@",self.bookid];
        }else{
            bookid = [NSString stringWithFormat:@"%@",self.dificultVC.bookId];
        }
        
        if (self.videoId) {
            videoId = [NSString stringWithFormat:@"%@",self.videoId];
        }else{
            videoId = [NSString stringWithFormat:@"%@",self.dificultVC.videoid];  //小i
        }
        
        dicss = @{@"videoId":videoId,@"userId":userId,@"bookId":bookid,@"flag":flag};
        NSLog(@"dicss%@",dicss);
        
        NSString *bd = [ToolObjc md5Str:dicss];
        dicVal = @{@"videoId":videoId,@"userId":userId,@"bookId":bookid,@"flag":flag,@"bd_sig":bd};
        //
        

        [[HttpConnctionManager sharedInstance]requestParam:dicVal andUrl:path andSuccessedBlock:^(NSDictionary *succeedResult) {
            NSLog(@"%@",succeedResult);
            if ([[NSString stringWithFormat:@"%@",[succeedResult valueForKey:@"resCode"]] isEqualToString:@"0"]){
                _videoId = [[succeedResult valueForKey:@"resData"]stringWithFilted:@"videoUrl"];
                //                NSLog(@":::::%@",_videoId);
                NSUSER_DEF_NORSET(_videoId, @"VIDEOURL");
                
                self.videoId = [[succeedResult valueForKey:@"resData"]stringWithFilted:@"videoId"];
                self.bookid = [[succeedResult valueForKey:@"resData"]stringWithFilted:@"bookId"];
                NSLog(@"~~~~~~~~~~~~%@",_videoId);
                
                self.dificultVC.name.text = [[succeedResult valueForKey:@"resData"]stringWithFilted:@"bookName"];
                self.dificultVC.classes.text = [[succeedResult valueForKey:@"resData"]stringWithFilted:@"grade"];
                self.dificultVC.object.text = [[succeedResult valueForKey:@"resData"]stringWithFilted:@"subject"];
                self.dificultVC.infDes.text = [[succeedResult valueForKey:@"resData"]stringWithFilted:@"videoProfile"];
                
              
                [[NSNotificationCenter defaultCenter] removeObserver:self];
                
                [self.playerItem removeObserver:self forKeyPath:@"status"];
                //    self.player = nil;
                //    self.playerItem = nil;
                NSString *urlStr = [NSString stringWithFormat:@"%@", NSUSER_DEF(@"VIDEOURL")];
                
                NSURL *sourceMovieURL = [NSURL URLWithString:urlStr];
                
                
                AVAsset *movieAsset = [AVURLAsset URLAssetWithURL:sourceMovieURL options:nil];
                self.playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];
                //                self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
                
                [self.playerItem addObserver:self
                                  forKeyPath:@"status"
                                     options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew
                                     context:AVPlayerDemoPlaybackViewControllerStatusObservationContext];
                [self.player replaceCurrentItemWithPlayerItem:self.playerItem];
                                [self.player play];
                
                //                _slider.value = 0;
                
                //                [self updateValue:_slider];
                [[MBProgressController sharedInstance]hide];

                
            }
            
            
            //            //
        } andFailedBlock:^(AFHTTPRequestOperation *response, NSError *error) {
            //
            //            [_loading stopAnimating];
            //            _loading.hidden = YES;
            [[MBProgressController sharedInstance]hide];

        }];
        //
        [[MBProgressController sharedInstance]hide];
    }
}

@end
